package sql

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"regexp"
	"sort"
	"strings"

	"github.com/jedib0t/go-pretty/table"
)

var (
	EscapeTableRe = regexp.MustCompile(`[^\w!\.]`)
)

// SplitAtCommas split s at commas, ignoring commas in strings.
func SplitAtCommas(s string) []string {
	res := []string{}
	var beg int
	var inString bool

	for i := 0; i < len(s); i++ {
		if s[i] == ',' && !inString {
			res = append(res, strings.TrimSpace(s[beg:i]))
			beg = i + 1
		} else if s[i] == '\'' {
			if !inString {
				inString = true
			} else if i > 0 {
				inString = false
				if i > 0 && s[i-1] == '\\' {
					inString = true
				}
			}
		}
	}
	return append(res, s[beg:])
}

func Debug(args interface{}) string {
	log.Println(args)
	sR := bufio.NewReader(os.Stdin)
	line, _, _ := sR.ReadLine()
	return strings.TrimSpace(string(line))
}

func ColorT(args []Dict) {
	t := table.NewWriter()
	t.SetOutputMirror(os.Stdout)
	all := 0
	var headers table.Row
	var keys []string
	for no, arg := range args {
		// var data map[string]interface{}
		// yellow := FGCOLORS[0]
		var values table.Row
		if no == 0 {
			for k := range arg {
				keys = append(keys, k)
			}
			sort.Slice(keys, func(i, j int) bool {
				ll := len(keys[i])
				rl := len(keys[j])
				if ll == rl {
					return byte(keys[i][0]) < byte(keys[j][0])
				} else {
					return ll < rl
				}
			})
			for _, k := range keys {
				headers = append(headers, k)
				values = append(values, fmt.Sprint(arg[k]))
			}
		} else {
			for _, k := range headers {
				values = append(values, fmt.Sprint(arg[k.(string)]))
			}
		}
		if no == 0 {
			t.AppendHeader(headers)
		}
		t.AppendRow(values)
		// if b, err := json.Marshal(arg); err == nil {

		// if err := json.Unmarshal(b, &data); err == nil {

		// }
		// }
		all = no + 1
	}
	t.AppendFooter(table.Row{"Total", all})
	t.SetStyle(table.StyleLight)
	t.Render()
}

func GetMapKeys(some map[string]interface{}) (keys []string) {
	for k := range some {
		keys = append(keys, k)
	}
	sort.Slice(keys, func(i, j int) bool {
		l := byte(keys[i][0])
		r := byte(keys[j][0])
		if l == r {
			return len(keys[i]) < len(keys[j])
		} else {
			return l < r
		}
	})
	return
}
